<?php
/***********************************************strat物流API***************************************************/ 
	/**
	 *  taobao.areas.get:查询标准地区码   [查]
	 * */
	 function TOP_AreasGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,areasGet); 
	 }
	 /**
	 *  taobao.logistics.companies.get:查询物流公司信息   [查]
	 * */
	 function TOP_LogisticsCompaniesGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,logisticsCompaniesGet); 
	 }
	 /**
	 *  taobao.delivery.send:发货处理    [高]
	 * */
	 function TOP_DeliverySend($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,deliverySend); 
	 }
	 /**
	 *  taobao.logistics.orders.get:批量查询物流订单   [买]
	 * */
	 function TOP_LogisticsOrdersGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,logisticsOrdersGet); 
	 }
	 /**
	 *  taobao.logistics.orders.detail.get:批量查询物流订单,返回详细信息   [商]
	 * */
	 function TOP_LogisticsOrdersDetailGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,logisticsOrdersDetailGet,'ship'); 
	 } 

/*************************************************end物流API***************************************************/ 




	/**
	 *  taobao.areas.get:查询标准地区码  [查]
	 *  Area 向taobao地区表中插入数量
	 * */
	function InsertIntoTB_area()
	{
		global $exc,$db,$os,$topParamArr;  
		$exc = new exchange($os->table('tb_area'), $db, 'id', 'area_id');
		$array_sys=$topParamArr;
     	$array_sys['method']='taobao.areas.get';
     	$userParamArr = array(
			'fields' => 'area_id,area_type,area_name,parent_id,zip',
	 	); 
		$results = lib_getArray_params( $array_sys + $userParamArr); 
		foreach ( $results['area'] as $result )
		{
			$tb_area = array(
			'area_id'           => $result['area_id'] ,
			'area_type'          => $result['area_type'] ,
			'area_name'      => $result['area_name'] ,
			'parent_id'      => $result['parent_id'] ,
			'zip'      => $result['zip'] ,
			'field1'   =>$db->getOne("select region_id from open_region r where region_name like '%".$result['area_name']."%'" )  //自动关联商城的地区表
			);  
		  if(!$exc->is_only('area_id',  $result['area_id']  ) ){     
				$db->autoExecute($os->table('tb_area'), $tb_area, 'UPDATE', " area_id = '$result[area_id]'");
		    }
		    else{ 
		    	$db->autoExecute($os->table('tb_area'), $tb_area, 'INSERT');
		    }    
		} 
	}
    /**
     * taobao.logistics.companies.get:查询物流公司信息  [查]
     * logistic_company 向taobao配送方式插入
     * */
    function InsertIntoTB_shipping()  { 
 		global  $db,$os ;   
     	$userParamArr = array(
						'fields' => 'company_id,company_code,company_name',
			 		);   
 		$results = TOP_LogisticsCompaniesGet( $userParamArr ); 
		foreach ( $results['logistic_company'] as $result )
		{
			$result[field1]=$db->getOne("select shipping_code from open_shipping where shipping_name like '%".$result['company_name']."%'; " ) ; //自动关联商城的配送方式
			OS_InsertIntoTB('tb_shipping','company_code',$result);
		 } 
    } 
    /**
     *  taobao.delivery.send:发货处理    [高]
     *  调用taobao的发货处理   taobao.delivery.send   
     *  tid  交易ID  order_type 发货类型. 可选( delivery_needed(物流订单发货),virtual_goods(虚拟物品发货). ) 注:选择virtual_goods类型进行发货的话下面的参数可以不需填写。 
     *  company_code 物流公司代码.如"POST"就代表中国邮政,"ZJS"就代表宅急送
     *  out_sid   运单号.具体一个物流公司的真实运单号码
     *  seller_name 卖家姓名 
     *  seller_area_id 卖家所在地国家公布的标准地区码.参考:http://www.stats.gov.cn/tjbz/xzqhdm/t20080215_402462675.htm 或者调用 taobao.areas.get 获取 
     *  seller_address  卖家地址(详细地址).如:XXX街道XXX门牌,省市区不需要提供. 
     *  seller_zip 卖家邮编 seller_phone 卖家固定电话.包含区号,电话,分机号,中间用 " – "; 卖家固定电话和卖家手机号码,必须填写一个.
     *  seller_mobile  卖家手机号码   memo  卖家备注.最大长度为250个字符. 
     * */
 	function taobaoSendOrder($order_sn,$out_sid='')
    {
    	 global $_CFG, $db,$os ;  
    	 $sql="select * from open_order_info as oi 
			  left join open_tb_trade as tb_t on tb_t.outer_order_sn=oi.order_sn where order_sn='".$order_sn."'  limit 1"; //tid,invoice_no,order_id,mobile 
		 $row = $db->getRow($sql);
    	 if( $row && $row['merge_from'] ){
    	 	 $merge_from= $row['merge_from']; //如果存在
    	 	 $order_ids = explode(',',$merge_from); 
    	 	 $merge_order_sn = $order_sn;  
    	 	 if( is_array($order_ids) ){
    	 	 	 foreach ($order_ids as $order_id ){
    	 	 	 	$r_out_sid = $row['invoice_no']; 
    	 	 	   	$r_order_sn=Check_is_exist('order_info','order_id',$order_id,'','order_sn')	; 
    	 	 	   	taobaoSendOrder($r_order_sn , $r_out_sid );  //递归调用taobao发货
    	 	 	 }
    	 	 	  echo $merge_order_sn."发货完成!<br/>";
    	 	 	  return ; 
    	 	 } 
    	 } 
         if( $row && $row['tid'] ){
         	$tid=$row['tid'] ;  //交易ID
         	$order_type = "delivery_needed";   //发货类型
            if(!$out_sid) $out_sid = $row['invoice_no'] ;   // 运单号.具体一个物流公司的真实运单号码 
            $memo = $db->getOne( "select action_note from ".$os->table('order_action')." where shipping_status=1 and order_id=' $row[order_id]'" )     ;//'test备注';
 		    if(!$memo) $memo="备注测试";
            $seller_name = $_CFG['taobao_user'] ;	//卖家姓名
            if(!$seller_name) $seller_name="卖家姓名测试";
         	$seller_phone = $_CFG['service_phone']  ;  // $row['tel'] ;
         	if(!$seller_phone) $seller_phone="189999888";
         	$seller_address = $_CFG['shop_address']  ;   
            if(!$seller_address) $seller_address="上海百胜大楼";
         	$seller_mobile = $seller_phone ;    
         	$area_row =  $db->getRow("select * from open_tb_area where area_type=3 and area_name like (select CONCAT('%',region_name,'%') as a  from open_region  where region_id= '$_CFG[shop_city]')"); // '330300';		// $row['zipcode'] ;
         	$seller_zip =$area_row['zip'];
         	$seller_area_id = $area_row['area_id'];; //卖家所在地国家公布标准地区码通过taobao.areas.get获取  温州 
         	$sql="select company_code from open_shipping sp left join open_tb_shipping tb_sp on sp.shipping_code= tb_sp.field1 where sp.shipping_id='$row[shipping_id]'";
         	$company_code = $db->getOne($sql); 
         	if(!$company_code)  {
         		InsertIntoTB_shipping();  //调用TOP得到物流公司关联
         		$company_code = $db->getOne($sql);      //返回 taobao所需的物流公司编码 
         	} 
         	if( !$company_code ) {
         		 echo ('shippping_id'.$row[shipping_id].'快递公司未关联<br/>'); 
         		 return ;
         	}
         	if( !$out_sid ){
         		 echo('没有外部运单号');
         		 return ;
         	} 
         	Update_table_key('tb_trade','status','WAIT_SELLER_SEND_GOODS',"tid='".$tid."'");  //发货前先改成等待商家发货
			$userParamArr = array(
									'tid' => $tid ,// '2640792933', //
									'order_type' => $order_type,  
									'company_code' => $company_code, 
									'out_sid' => $out_sid,
									'seller_name' => $seller_name,
									'seller_area_id' => $seller_area_id,
									'seller_address' => $seller_address,
									'seller_zip' => $seller_zip,
									'seller_phone' => $seller_phone,
									'seller_mobile' => $seller_mobile,
								    'memo' => $memo 
							 	);  
		 	$result  =TOP_DeliverySend($userParamArr);	
			if($result[code]){//写出错日志 
				echo ($order_sn.'['.$tid.']'.'TOP_DeliverySend方法请求失败!'.':['.$result[code].']'.$result[msg] . ' <a herf="#" onclick="history.go(-1)">返回</a><br/>'); 
				if($result[msg]=='Shipping parameter error:该物流订单已经发货，不能重复发货') Update_table_key('tb_trade','status','WAIT_BUYER_CONFIRM_GOODS',"tid='".$tid."'"); 
				if($result[msg]=='Shipping parameter error:物流订单不存在') Update_table_key('tb_trade','status','WAIT_BUYER_CONFIRM_GOODS',"tid='".$tid."'"); 
				//return $result;
			}else {
				echo ($order_sn.'['.$tid.']'.'taobao发货成功 <a href="#" onclick="history.go(-1)">返回</a><br/>');  //并更改tb_trade 发货状态  status  String  //WAIT_BUYER_CONFIRM_GOODS
				Update_table_key('tb_trade','status','WAIT_BUYER_CONFIRM_GOODS',"tid='".$tid."'"); //发货成功更新状态为等待买家确认
			}
         }else {
         	  //  echo $sql." <br/>订单:".$order_sn." 没有关联的top交易号<br/>";
         }		 
    }
    /**
	 * taobao.logistics.orders.detail.get:批量查询物流订单,返回详细信息  [商]
	 * 根据 订单号tid 得到物流相关信息  
	 * */
	function GetMyShippingByTid($tid){ 
			if( $tid ){
				$userParamArr = array(
								'fields' => 'tid,seller_nick,buyer_nick,delivery_start,delivery_end,out_sid,item_title,receiver_name,receiver_phone,receiver_mobile,receiver_location,status,type,freight_payer,seller_confirm,company_name' ,
								'tid'   => $tid,
							);  
				$results = TOP_LogisticsOrdersDetailGet($userParamArr);  
				if($results['ship']) OS_InsertIntoTB("tb_my_shipping",'tid',$results['ship']);
			}   
//			print_r($results['ship']);
			return $results;
	 } 
	  

?>